package com.tanhua.server.service;

import com.tanhua.commons.constant.Constants;
import com.tanhua.dubbo.api.db.*;
import com.tanhua.model.db.*;
import com.tanhua.model.vo.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lamy
 * @version 1.0
 * @ClassName: SoulService
 * @date 2021-12-26 20:16:29
 */
@Service
public class SoulService {
    @DubboReference
    private QuestionNaireApi questionNaireApi;

    @DubboReference
    private ProblemApi problemApi;

    @DubboReference
    private OptionApi optionApi;

    @DubboReference
    private PersonalityApi personalityApi;

    @DubboReference
    private ReportApi reportApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;

    //测灵魂-问卷列表
    public List<QuestionnaireVo> findQuestionNaire() {
        //构造返回对象List<QuestionnaireVo>
        List<QuestionnaireVo> voList = new ArrayList<>();
        //查询所有问卷表
        List<Questionnaire> questionnaireList = questionNaireApi.findAll();


        //判断是否中、高级表是否被锁
        String key = Constants.SOUL_TEST_KEY + UserHolder.getUserId();

        String userLevel = stringRedisTemplate.opsForValue().get(key);


        //循环遍历问卷表
        for (Questionnaire questionnaire : questionnaireList) {

            //根据当前问卷表得到该问卷表的问题集problemIds
            String problemId = questionnaire.getProblemIds();
            String[] split = problemId.split(",");
            List<String> problemIds = Arrays.stream(split).collect(Collectors.toList());
            //构造questionnaireVo对象
            QuestionnaireVo questionnaireVo = new QuestionnaireVo();
            //设置问卷的id
            questionnaireVo.setId(questionnaire.getId().toString());
            BeanUtils.copyProperties(questionnaire, questionnaireVo);

            // 判断问卷等级
            if ("初级".equals(questionnaireVo.getLevel()) ) {
                //初级问卷直接解锁
                questionnaireVo.setIsLock(0);
            }else if ("中级".equals(userLevel) && "中级".equals(questionnaireVo.getLevel())){
                questionnaireVo.setIsLock(0);
            }else if ("高级".equals(userLevel)){
                questionnaireVo.setIsLock(0);
            }

            //构造List<ProblemVo>
            List<ProblemVo> problemVoList = new ArrayList<>();
            //根据问题ids循环查找问题添加到问题集合
            for (String id : problemIds) {
                Problem problem = problemApi.findAll(Long.valueOf(id));
                //根据问题的id来查询对应的选项
                List<Option> optionList = optionApi.findAll(problem.getId());
                //构造List<OptionsVo>
                List<OptionsVo> optionsVoList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(optionList)) {
                    for (Option option : optionList) {
                        //得到List<OptionsVo>
                        OptionsVo optionsVo = OptionsVo.init(option);
                        optionsVoList.add(optionsVo);
                    }
                }
                ProblemVo problemVo = ProblemVo.init(problem, optionsVoList);
                problemVoList.add(problemVo);
            }
            // 获取报告
            Report report = reportApi.findOne(questionnaire.getId(), UserHolder.getUserId());
            if (null != report){
                questionnaireVo.setReportId(report.getId().toString());
            }
            questionnaireVo.setQuestions(problemVoList);
            //得到List<questionnaireVo>
            voList.add(questionnaireVo);
        }
        return voList;
    }
    //hashMaps={  {"questionId","1","optionId","2"},{"questionId","2","optionId","2"} ,  }

    //测灵魂-提交问卷 把结果表填充完成
    public String submitQuestionNaire(List<Map<String, String>> hashMaps) {
        List<Long> questionIds = new ArrayList<>();
        List<Long> optionIds = new ArrayList<>();
        //构造report对象
        Report report = new Report();
        report.setUserId(UserHolder.getUserId());

        for (Map<String, String> hashMap : hashMaps) {
            Long questionId = Long.valueOf(hashMap.get("questionId"));
            Long optionId = Long.valueOf(hashMap.get("optionId"));

            questionIds.add(questionId);
            optionIds.add(optionId);

            Problem problem = problemApi.findAll(questionId);
            report.setQuestionnaireId(problem.getQuestionnaireId());
            report.setLevel(problem.getLevel());
        }
        //总分
        int totalScore = 0;
        //理性值分数
        int rationalScore = 0;
        //感性值分数
        int perceptualScore = 0;
        //外向值分数
        int extroversionScore = 0;
        //判断值分数
        int judgeScore = 0;

        for (Long optionId : optionIds) {
            Option option = optionApi.getOption(optionId);
            totalScore += option.getScore();
            rationalScore += option.getRational();
            perceptualScore += option.getPerceptual();
            extroversionScore += option.getExtroversion();
            judgeScore += option.getJudge();
        }
        Personality personality = personalityApi.findPersonality(totalScore);

        report.setScore(totalScore);
        report.setCover(personality.getCover());
        report.setConclusion(personality.getType());
        report.setRational(rationalScore);
        report.setPerceptual(perceptualScore);
        report.setExtroversion(extroversionScore);
        report.setJudge(judgeScore);


        String reportId = reportApi.insert(report);
        String level = report.getLevel();

        if ("初级".equals(level)) {
            String key = Constants.SOUL_TEST_KEY + UserHolder.getUserId();
            stringRedisTemplate.opsForValue().set(key, "中级");
        }

        if ("中级".equals(level)) {
            String key = Constants.SOUL_TEST_KEY + UserHolder.getUserId();
            stringRedisTemplate.opsForValue().set(key, "高级");
        }

        return reportId;
    }

    //查看结果
    public SoulResultVo soulResult(Long id) {
        Report report = reportApi.findReport(id);
        SoulResultVo soulResultVo = SoulResultVo.init(report);
        //当前用户的报告总分
        Integer score = report.getScore();
        // 分数上限
        Integer maxScore = score + 5;
        // 分数下限
        Integer minScore = score - 5;
        // 查找相似用户Ids
        List<Long> userIds = reportApi.findUsers(maxScore, minScore,report);
        if (!CollectionUtils.isEmpty(userIds)){
            //根据相似用户Ids返回相似用户信息map集合
            Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
            //构造List<SimilarVo>
            List<SimilarVo> similarVos = new ArrayList<>();
            for (Long userId : userIds) {
                UserInfo userInfo = userInfoMap.get(userId);
                SimilarVo similarVo = SimilarVo.init(userInfo);
                similarVos.add(similarVo);
            }
            soulResultVo.setSimilarYou(similarVos);
        }else {
            soulResultVo.setSimilarYou(null);
        }
        return soulResultVo;
    }
}
